<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车架号" prop="vin">
        <el-input
          v-model="queryParams.vin"
          placeholder="请输入车架号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评估单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入评估单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select  v-model="queryParams.status"
                    placeholder="请选择状态" clearable>
          <el-option v-for="(value, key) in statusType"
                     :key="key"
                     :label="value"
                     :value="key"
          >
          </el-option>
        </el-select>
      </el-form-item>


<!--      <el-form-item label="评估价" prop="price">-->
<!--        <el-input-->
<!--          v-model="queryParams.price"-->
<!--          placeholder="请输入评估价"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="报告地址" prop="pdfUrl">-->
<!--        <el-input-->
<!--          v-model="queryParams.pdfUrl"-->
<!--          placeholder="请输入报告地址"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['asset:record:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['asset:record:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['asset:record:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['asset:record:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList">
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="车架号" align="center" prop="vin" width="180"/>
      <el-table-column label="评估单号" align="center" prop="orderNo" width="180"/>
      <el-table-column label="评估价" align="center" prop="price" />

      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          {{statusType[scope.row.status]}}
        </template>
      </el-table-column>
<!--      <el-table-column label="车牌号" align="center" prop="carp" >-->
<!--        <template slot-scope="scope">-->
<!--          {{ JSON.parse(scope.row.responseText).plateNumber}}-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="车辆信息" align="center" prop="carMes" show-overflow-tooltip>-->
<!--        <template slot-scope="scope">-->
<!--          {{getCarMes(scope.row.responseText)}}-->
<!--        </template>-->
<!--      </el-table-column>>-->
<!--      <el-table-column label="报告地址" align="center" prop="pdfUrl" />-->
      <el-table-column label="评估来源" align="center" prop="sourceType" >
        <template slot-scope="scope">
          {{assetType[scope.row.sourceType]}}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createByName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.status == 1"
            @click="showPDF(scope.row)"
          >查看报告</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.status < 2 && scope.row.sourceType == 1"
            @click="showData(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.status == 0 && scope.row.sourceType == 1"
            @click="refreshData(scope.row)"
          >刷新</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.status == 2 && scope.row.sourceType == 1"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['asset:record:edit']"
          >修改</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['asset:record:remove']"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改评估记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" :width="isMobile ?'90%':'60%'" append-to-body>
      <div v-if="form.id != null && canEdit" style="color: red">驳回原因：{{form.rejectReason}}</div>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="top">
        <el-form-item label="评估方" prop="sourceType"  v-if="form.id == null">
          <el-select v-model="form.sourceType"
                     style="width: 300px"
                     :disabled="!canEdit"
                      placeholder="请选择状态" clearable>
            <el-option v-for="(value,key) in assetType"
                       :key="key"
                       :label="value"
                       :value="key"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <div v-if="form.sourceType == 0">

          <el-form-item label="车架号" prop="vin" >
            <el-input v-model="form.vin" style="width: 300px" placeholder="请输入车架号" />
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label="车辆类型" prop="carType" >
            <el-select v-model="form.carType"
                       style="width: 150px"
                       @change="carTypeClick"
                       :disabled="!canEdit"
                       placeholder="请选择状态" clearable>
              <el-option v-for="(value, index) in carTypeArr"
                         :key="index"
                         :label="value.templateName"
                         :value="value.templateName"
              >
              </el-option>
            </el-select>
            <el-select v-model="form.carTypeSub"
                       style="width: 150px"
                       :disabled="!canEdit"
                       @change="carTypeSubClick"
                       placeholder="请选择状态" clearable>
              <el-option v-for="(value, index) in carTypeSubArr"
                         :key="value.templateId"
                         :label="value.templateName"
                         :value="value.templateId"
              >
              </el-option>
            </el-select>
          </el-form-item>


          <div v-for="(item ,index) in form.tempArr" >
            <el-divider>{{item.group}}</el-divider>
            <el-form-item :label="subItem.label" :prop="subItem.isMust == 1 ? 'need':subItem.id" v-for="(subItem,subIndex) in item.items">

              <el-date-picker
                :disabled="!canEdit"
                v-if="subItem.type.indexOf('input:date') > -1"
                v-model="form.data[subItem.id]"
                style="width: 300px"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期">
              </el-date-picker>

              <el-select  v-model="form.data[subItem.id]"
                          v-else-if="subItem.type == 'select'"
                         style="width: 300px"
                          :disabled="!canEdit"
                         placeholder="请选择状态" clearable>
                <el-option v-for="(value, index) in subItem.data"
                           :key="index"
                           :label="value.value"
                           :value="value.key"
                >
                </el-option>
              </el-select>

              <div v-else-if="subItem.type == 'select:addr'">
                <el-select
                  v-model="form.data['province']"
                  style="width: 150px"
                  :disabled="!canEdit"
                  @change="changeProvicne"
                  placeholder="请选择状态" clearable>
                  <el-option v-for="(value, index) in provinces"
                             :key="index"
                             :label="value.name"
                             :value="value.code"
                  >
                  </el-option>
                </el-select>

                <el-select  v-model="form.data[subItem.id]"
                            style="width: 150px"
                            :disabled="!canEdit"
                            @change="changeCity"
                            placeholder="请选择状态" clearable>
                  <el-option v-for="(value, index) in citys"
                             :key="index"
                             :label="value.name"
                             :value="value.code"
                  >
                  </el-option>
                </el-select>
              </div>


            <el-input
              style="width: 300px"
              :disabled="!canEdit"
              v-else-if="subItem.type.indexOf('input') > -1 || subItem.type.indexOf('textarea') > -1"
              :type="(subItem.type.indexOf('textarea') > -1) ? 'textarea' : 'text'"
              v-model="form.data[subItem.id]">
              <template slot="append" v-if="subItem.unit != null">{{subItem.unit}}</template>
            </el-input>
              <Car300ImageUpload
                v-else-if="subItem.type.indexOf('file-image') > -1"
                v-model="form.data[subItem.id]"
                :id="subItem.id"
                :token="token"
                :is-show="!canEdit"
                :titleLabel="subItem.label"
                :baseUrl="baseUrl"
              />
            </el-form-item>

<!--            <el-select  v-model="form.data[subItem.id]"-->
<!--                        v-else-if="subItem.type.indexOf('select') > -1"-->
<!--                        style="width: 300px"-->
<!--                        @change="carTypeClick"-->
<!--                        placeholder="请选择状态" clearable>-->
<!--              <el-option v-for="(value, index) in subItem.data"-->
<!--                         :key="index"-->
<!--                         :label="value.value"-->
<!--                         :value="value.key"-->
<!--              >-->
<!--              </el-option>-->
<!--            </el-select>-->
          </div>

        </div>


<!--        <el-form-item label="评估单号" prop="orderNo">-->
<!--          <el-input v-model="form.orderNo" placeholder="请输入评估单号" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="评估价" prop="price">-->
<!--          <el-input v-model="form.price" placeholder="请输入评估价" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="响应数据" prop="responseText">-->
<!--          <el-input v-model="form.responseText" type="textarea" placeholder="请输入内容" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="报告地址" prop="pdfUrl">-->
<!--          <el-input v-model="form.pdfUrl" placeholder="请输入报告地址" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="btnLoading" v-if="canEdit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRecord, getRecord, delRecord, addRecord, updateRecord,
  getSqCarType, getSqTempDetail, getQiniuToken, getSQDetail
} from "@/api/asset/record"
import Car300ImageUpload from '@/components/QiniuImageUpload'
import {city, provinces} from "@/api/common/common";
import Vue from 'vue'

export default {
  name: "Record",
  components: { Car300ImageUpload },
  data() {
    return {
      canEdit: true,
      // 遮罩层
      loading: true,
      token: "",
      baseUrl: "",
      // 选中数组
      ids: [],
      provinces:[],
      citys:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 评估记录表格数据
      recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 评估来源时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        vin: null,
        orderNo: null,
        price: null,
        responseText: null,
        pdfUrl: null,
        sourceType: null,
        createTime: null,
      },
      btnLoading: false,
      // 表单参数
      form: {},
      assetType: {
        // 0:'赋界',
        1:'车正'
      },
      statusType: {
        0:'评估中',
        1:'已评估',
        2:'已驳回'
      },
      carTypeArr:[],
      carTypeSubArr:[],
      tempArr: [],
      // 表单校验
      rules: {
        sourceType:[{ required: true, message: "请选择", trigger: "blur" }],
        vin: [{ required: true, message: "请输入", trigger: "blur" }],
        need: [{ required: true, message: "请选择", trigger: "blur" }],
        carType:[{ required: true, message: "请选择", trigger: "blur" }]
      },
    }
  },
  created() {
    this.getList()
    provinces().then(response => {
      this.provinces = response.data
    })
    getSqCarType().then(response => {
      this.carTypeArr = response.data
    })

    // 获取七牛的token
    getQiniuToken().then((res) => {
      this.token = res.data.token;
      this.baseUrl = res.data.url
    });
  },
  computed:{
    isMobile(){
      return this.$store.state.app.device == 'mobile'
    }
  },
  methods: {
    changeProvicne(val) {
      for (let value of this.provinces) {
        if (value.code == val) {
          this.form.data.provinceName = value.name
        }
      }

      city(val).then(response => {
        this.citys = response.data
      })
    },
    changeCity(val) {
      for (let value of this.citys) {
        if (value.code == val) {
          this.form.data.cityName = value.name
        }
      }
    },
    carTypeClick(val) {
      for (let value of this.carTypeArr) {
        if (value.templateName == val) {
          this.form.carTypeSub = null
          this.carTypeSubArr = value.childTemplates
        }
      }
    },
    carTypeSubClick(val) {
      getSqTempDetail(val).then(response => {
        this.form.tempArr = response.data
      })
    },
    getCarMes(str) {
      let parse = JSON.parse(str);
      return parse.modelName
    },
    refreshData(row) {
      getSQDetail(row.id).then(response => {

      })
    },
    showPDF(row) {
      if (row.pdfUrl == null) {
        this.$message.error('暂无报告')
        return
      }
      if (this.isMobile) {
        window.location.href =  row.pdfUrl
      } else {
        window.open( row.pdfUrl)
      }
    },
    /** 查询评估记录列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0]
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1]
      }
      listRecord(this.queryParams).then(response => {
        this.recordList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        vin: null,
        orderNo: null,
        price: null,
        responseText: null,
        pdfUrl: null,
        createBy: null,
        sourceType: null,
        createTime: null,
        updateTime: null,
        //车辆类型
        carType: null,
        carTypeSub: null,
        data:{},
        tempArr: null,
        need:'3'
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.canEdit = true
      this.title = "添加评估记录"
    },
    showData(row) {
      this.handleUpdate(row)
      this.title = "评估详情"
      this.canEdit = false
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.canEdit = true
      const id = row.id || this.ids
      getRecord(id).then(response => {
        let data = JSON.parse(response.data.responseText)
        this.form.carType = ""
        this.form.carTypeSub = data.templateId
        getSqTempDetail(this.form.carTypeSub).then(response => {
          this.form.tempArr = response.data
        })
        //查询类型
        for (let item of this.carTypeArr) {
          let subArr = item.childTemplates
          for (let subItem of subArr) {
            if (subItem.templateId == this.form.carTypeSub) {
              this.carTypeSubArr = subArr
              this.form.carType = item.templateName
              break
            }
          }
        }
        this.form.sourceType = response.data.sourceType.toString()
        for (const key in data.values) {
          if (data.values[key].indexOf('https') > -1) {
            Vue.set(this.form.data, key, [{url:data.values[key]}])
          } else {
            Vue.set(this.form.data, key, data.values[key])
          }
        }
        let address = JSON.parse(data.values.parkingLot)
        //省市
        for(let item of this.provinces) {
          if (item.code == address.provinceCode) {
            Vue.set(this.form.data,'province', item.code)
            Vue.set(this.form.data,'parkingLot', address.cityCode)
            this.changeProvicne(item.code)
          }
        }
        this.form.id = response.data.id
        this.form.rejectReason = response.data.rejectReason
        this.open = true

      })
      this.title = "修改评估"
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
          this.btnLoading = true
            addRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            }).finally(() => {
              this.btnLoading = false
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除评估记录编号为"' + ids + '"的数据项？').then(function() {
        return delRecord(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('asset/record/export', {
        ...this.queryParams
      }, `record_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
